package kr.pe.johnkim.checkmileage.mobile.rest.controller;

import kr.pe.johnkim.checkmileage.mobile.domain.CheckMileageMember;
import kr.pe.johnkim.checkmileage.mobile.domain.CheckMileageMerchantMarketing;
import kr.pe.johnkim.checkmileage.mobile.domain.CheckMileageMileage;
import kr.pe.johnkim.checkmileage.mobile.rest.service.CheckMileageMemberService;
import kr.pe.johnkim.checkmileage.mobile.rest.service.CheckMileageMerchantMarketingService;
import kr.pe.johnkim.checkmileage.mobile.rest.service.CheckMileageMileageService;
import kr.pe.johnkim.checkmileage.mobile.util.CheckMileageCommon;
import org.codehaus.jettison.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

/**
 * Check Mileage 마케팅 관련 Controller 클래스 이다.
 *
 * @author : johnkim <cale9797@gmail.com / Bettersoft, Inc.>
 * @date: 12. 10. 20.
 */

@Controller
@Path("/checkMileageMerchantMarketingController")
public class CheckMileageMerchantMarketingController {

    // SLF4J Logging
    private Logger logger = LoggerFactory.getLogger(CheckMileageMerchantMarketingController.class);

    @Autowired
    private CheckMileageMerchantMarketingService checkMileageMerchantMarketingService = null;

    @Autowired
    private CheckMileageMileageService checkMileageMileageService = null;

    @Autowired
    private CheckMileageMemberService checkMileageMemberService = null;

    @Autowired
    private CheckMileageCommon checkMileageCommon = null;

    /**
     * 마케팅을 등록 한다.
     *
     * @param is
     * @return
     * @throws Exception
     */
    @POST
    @Path("/registerMarketing")
    @Consumes({"application/json", "application/xml"})
    @Produces({"application/json", "application/xml"})
    public CheckMileageMerchantMarketing registerMarketing(InputStream is) throws Exception {
        logger.info("registerMarketing");

        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = br.readLine();

        logger.info("line : {}", line);

        JSONObject jsonMileage = new JSONObject(line);
        JSONObject jsonMileage2 = jsonMileage.getJSONObject("checkMileageMerchantMarketing");

        CheckMileageMerchantMarketing parameterMerchantMarketing = new CheckMileageMerchantMarketing();

        parameterMerchantMarketing.setSubject(jsonMileage2.getString("subject"));
        parameterMerchantMarketing.setContent(jsonMileage2.getString("content"));
        parameterMerchantMarketing.setImageFileUrl(jsonMileage2.getString("imageFileUrl"));
        parameterMerchantMarketing.setActivateYn(jsonMileage2.getString("activateYn"));
        parameterMerchantMarketing.setModifyDate(jsonMileage2.getString("modifyDate"));
        parameterMerchantMarketing.setRegisterDate(jsonMileage2.getString("registerDate"));
        parameterMerchantMarketing.setCheckMileageMerchantsMerchantId(jsonMileage2.getString("checkMileageMerchantsMerchantId"));

        logger.info("subject                         : {}", parameterMerchantMarketing.getSubject());
        logger.info("content                         : {}", parameterMerchantMarketing.getContent());
        logger.info("imageFileUrl                    : {}", parameterMerchantMarketing.getImageFileUrl());
        logger.info("activateYn                      : {}", parameterMerchantMarketing.getActivateYn());
        logger.info("modifyDate                      : {}", parameterMerchantMarketing.getModifyDate());
        logger.info("registerDate                    : {}", parameterMerchantMarketing.getRegisterDate());
        logger.info("checkMileageMerchantsMerchantId : {}", parameterMerchantMarketing.getCheckMileageMerchantsMerchantId());

        CheckMileageMerchantMarketing resultMerchantMarketing = new CheckMileageMerchantMarketing();

        try {
            checkMileageMerchantMarketingService.registerMarketing(parameterMerchantMarketing);
            resultMerchantMarketing.setResult("SUCCESS");

            /**
             * 마케팅 등록에 성공하면 등로된 사용자들에게 Push Notification 을 발송 한다.
             */
            CheckMileageMileage parameterMileage = new CheckMileageMileage();

            parameterMileage.setActivateYn(jsonMileage2.getString("activateYn"));
            parameterMileage.setCheckMileageMerchantsMerchantId(jsonMileage2.getString("checkMileageMerchantsMerchantId"));

            List<CheckMileageMileage> checkMileageMileageList = checkMileageMileageService.selectMerchantMemberMileageList(parameterMileage);

            for(int i=0 ; i<checkMileageMileageList.size() ; i++) {
                CheckMileageMember parameterMember = new CheckMileageMember();

                parameterMember.setCheckMileageId(checkMileageMileageList.get(i).getCheckMileageMembersCheckMileageId());
                parameterMember.setActivateYn("Y");

                CheckMileageMember resultMember = checkMileageMemberService.selectMemberInformation(parameterMember);

                String registrationId = resultMember.getRegistrationId();
                String receiveNotificationYn = resultMember.getReceiveNotificationYn();
                String deviceType = resultMember.getDeviceType();
                String languageCode = resultMember.getLanguageCode();
                String messageContents = "";

                logger.info("checkMileageId        : {}", parameterMember.getCheckMileageId());
                logger.info("activateYn            : {}", parameterMember.getActivateYn());
                logger.info("registrationId        : {}", registrationId);
                logger.info("receiveNotificationYn : {}", receiveNotificationYn);
                logger.info("deviceType            : {}", deviceType);
                logger.info("languageCode          : {}", languageCode);

                if((("AS").equals(deviceType)) && (("Y").equals(receiveNotificationYn)) && (!("").equals(registrationId))) {
                    // android mobile device 에 notification message 를 보낸다.
                    if((languageCode).equals("ko")) {
                        messageContents = "이벤트가 등록되었습니다.";
                    } else if((languageCode).equals("en")) {
                        messageContents = "New event.";
                    } else {
                        messageContents = "New event.";
                    }

                    checkMileageCommon.sendASMessage(registrationId, messageContents);
                } else if((("IP").equals(deviceType)) && (("Y").equals(receiveNotificationYn)) && (!("").equals(registrationId))) {
                    // iphone mobile device 에 notification message 를 보낸다.
                    if((languageCode).equals("ko")) {
                        messageContents = "이벤트가 등록되었습니다.";
                    } else if((languageCode).equals("en")) {
                        messageContents = "New event.";
                    } else {
                        messageContents = "New event.";
                    }

                    checkMileageCommon.sendIPMessage(registrationId, messageContents);
                }
            }
        } catch (Exception e) {
            resultMerchantMarketing.setResult("FAIL");
            logger.error("Fail to register marketing.");
        }

        return resultMerchantMarketing;
    }

    /**
     * 마케팅을 업데이트 한다.
     *
     * @param is
     * @return
     * @throws Exception
     */
    @POST
    @Path("/updateMarketing")
    @Consumes({"application/json", "application/xml"})
    @Produces({"application/json", "application/xml"})
    public CheckMileageMerchantMarketing updateMarketing(InputStream is) throws Exception {
        logger.info("updateMarketing");

        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = br.readLine();

        logger.info("line : {}", line);

        JSONObject jsonMileage = new JSONObject(line);
        JSONObject jsonMileage2 = jsonMileage.getJSONObject("checkMileageMerchantMarketing");

        CheckMileageMerchantMarketing parameterMerchantMarketing = new CheckMileageMerchantMarketing();

        parameterMerchantMarketing.setIdCheckMileageMerchantMarketings(jsonMileage2.getString("idCheckMileageMerchantMarketings"));
        parameterMerchantMarketing.setSubject(jsonMileage2.getString("subject"));
        parameterMerchantMarketing.setContent(jsonMileage2.getString("content"));
        parameterMerchantMarketing.setImageFileUrl(jsonMileage2.getString("imageFileUrl"));
        parameterMerchantMarketing.setActivateYn(jsonMileage2.getString("activateYn"));
        parameterMerchantMarketing.setModifyDate(jsonMileage2.getString("modifyDate"));
        parameterMerchantMarketing.setCheckMileageMerchantsMerchantId(jsonMileage2.getString("checkMileageMerchantsMerchantId"));

        logger.info("idCheckMileageMerchantMarketings : {}", parameterMerchantMarketing.getIdCheckMileageMerchantMarketings());
        logger.info("subject                          : {}", parameterMerchantMarketing.getSubject());
        logger.info("content                          : {}", parameterMerchantMarketing.getContent());
        logger.info("imageFileUrl                     : {}", parameterMerchantMarketing.getImageFileUrl());
        logger.info("activateYn                       : {}", parameterMerchantMarketing.getActivateYn());
        logger.info("modifyDate                       : {}", parameterMerchantMarketing.getModifyDate());
        logger.info("checkMileageMerchantsMerchantId  : {}", parameterMerchantMarketing.getCheckMileageMerchantsMerchantId());

        CheckMileageMerchantMarketing resultMerchantMarketing = new CheckMileageMerchantMarketing();

        try {
            checkMileageMerchantMarketingService.updateMarketing(parameterMerchantMarketing);
            resultMerchantMarketing.setResult("SUCCESS");
        } catch (Exception e) {
            resultMerchantMarketing.setResult("FAIL");
            logger.error("Fail to update marketing.");
        }

        return resultMerchantMarketing;
    }

    /**
     * 마케팅 목록을 가져 온다. 사용자 smart phone 에 출력.
     *
     * @param is
     * @return
     * @throws Exception
     */
    @POST
    @Path("/selectMemberMerchantMarketingList")
    @Consumes({"application/json", "application/xml"})
    @Produces({"application/json", "application/xml"})
    public List<CheckMileageMerchantMarketing> selectMemberMerchantMarketingList(InputStream is) throws Exception {
        logger.info("selectMemberMerchantMarketingList");

        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = br.readLine();

        logger.info("line : {}", line);

        JSONObject jsonMileage = new JSONObject(line);
        JSONObject jsonMileage2 = jsonMileage.getJSONObject("checkMileageMerchantMarketing");

        CheckMileageMerchantMarketing parameterMerchantMarketing = new CheckMileageMerchantMarketing();

        parameterMerchantMarketing.setCheckMileageId(jsonMileage2.getString("checkMileageId"));
        parameterMerchantMarketing.setActivateYn(jsonMileage2.getString("activateYn"));

        logger.info("checkMileageId : {}", parameterMerchantMarketing.getCheckMileageId());
        logger.info("activateYn     : {}", parameterMerchantMarketing.getActivateYn());

        return checkMileageMerchantMarketingService.selectMemberMerchantMarketingList(parameterMerchantMarketing);
    }

    /**
     * 마케팅 목록을 가져 온다. 가맹점 iPad/Web site 에 출력.
     *
     * @param is
     * @return
     * @throws Exception
     */
    @POST
    @Path("/selectMerchantMemberMarketingList")
    @Consumes({"application/json", "application/xml"})
    @Produces({"application/json", "application/xml"})
    public List<CheckMileageMerchantMarketing> selectMerchantMemberMarketingList(InputStream is) throws Exception {
        logger.info("selectMerchantMemberMarketingList");

        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = br.readLine();

        logger.info("line : {}", line);

        JSONObject jsonMileage = new JSONObject(line);
        JSONObject jsonMileage2 = jsonMileage.getJSONObject("checkMileageMerchantMarketing");

        CheckMileageMerchantMarketing parameterMerchantMarketing = new CheckMileageMerchantMarketing();

        parameterMerchantMarketing.setActivateYn(jsonMileage2.getString("activateYn"));
        parameterMerchantMarketing.setCheckMileageMerchantsMerchantId(jsonMileage2.getString("checkMileageMerchantsMerchantId"));

        logger.info("activateYn                       : {}", parameterMerchantMarketing.getActivateYn());
        logger.info("checkMileageMerchantsMerchantId  : {}", parameterMerchantMarketing.getCheckMileageMerchantsMerchantId());

        return checkMileageMerchantMarketingService.selectMerchantMemberMarketingList(parameterMerchantMarketing);
    }

    /**
     * 마케팅을 비활성화 한다.
     *
     * @param is
     * @return
     * @throws Exception
     */
    @POST
    @Path("/updateDeactivateMarketing")
    @Consumes({"application/json", "application/xml"})
    @Produces({"application/json", "application/xml"})
    public CheckMileageMerchantMarketing updateDeactivateMarketing(InputStream is) throws Exception {
        logger.info("selectMemberMerchantMarketingList");

        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = br.readLine();

        logger.info("line : {}", line);

        JSONObject jsonMileage = new JSONObject(line);
        JSONObject jsonMileage2 = jsonMileage.getJSONObject("checkMileageMerchantMarketing");

        CheckMileageMerchantMarketing parameterMerchantMarketing = new CheckMileageMerchantMarketing();

        parameterMerchantMarketing.setIdCheckMileageMerchantMarketings(jsonMileage2.getString("idCheckMileageMerchantMarketings"));
        parameterMerchantMarketing.setActivateYn(jsonMileage2.getString("activateYn"));
        parameterMerchantMarketing.setCheckMileageMerchantsMerchantId(jsonMileage2.getString("checkMileageMerchantsMerchantId"));

        logger.info("idCheckMileageMerchantMarketings : {}", parameterMerchantMarketing.getIdCheckMileageMerchantMarketings());
        logger.info("activateYn                       : {}", parameterMerchantMarketing.getActivateYn());
        logger.info("checkMileageMerchantsMerchantId  : {}", parameterMerchantMarketing.getCheckMileageMerchantsMerchantId());

        CheckMileageMerchantMarketing resultMerchantMarketing = new CheckMileageMerchantMarketing();

        try {
            checkMileageMerchantMarketingService.updateDeactivateMarketing(parameterMerchantMarketing);
            resultMerchantMarketing.setResult("SUCCESS");
        } catch (Exception e) {
            resultMerchantMarketing.setResult("FAIL");
            logger.error("Fail to update deactivate marketing.");
        }

        return resultMerchantMarketing;
    }
}
